import React from 'react';
import { observable, action, toJS } from 'mobx';
import {inject, observer} from 'mobx-react';
import {Row, Col, Input, Tabs, Button, Alert, Spin, Icon, Form, InputNumber, Modal, message} from 'antd'
import { WeaForm, WeaSwitch,WeaTableNew } from 'comsMobx';
import {
	WeaLocaleProvider,
	WeaErrorPage,
	WeaAlertPage,
	WeaTop,
	WeaTab,
	WeaInput,
	WeaLeftRightLayout,
	WeaSearchGroup,
	WeaRightMenu,
	WeaInputSearch,
	WeaBrowser,
	WeaSelect,
	WeaDialog,
	WeaFormItem,
	WeaProgress,
	WeaTools
} from 'ecCom'

const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;
const WeaTable = WeaTableNew.WeaTable;
const ButtonGroup = Button.Group;

@inject('DispatchSetStore')
@observer
class DispatchSet extends React.Component {
	constructor(props) {
		super(props);
	}
	componentDidMount() {//一些初始化请求
		const { DispatchSetStore } = this.props;
		//初始化列表
		DispatchSetStore.doSearch();
		DispatchSetStore.getRightMenu();
		DispatchSetStore.getConditionInfo();
	}
	componentWillReceiveProps(nextProps) {
	}

	componentWillUnmount() {
		//组件卸载时一般清理一些状态
	}

	render() {
		const { DispatchSetStore } = this.props;
		const { sessionkey, setShowSearchAd,loading , form,tableStore ,showSearchAd ,hasRight,setQuickSearchValue,dialogtitle,visible,dialogtitle1,visible1  } = DispatchSetStore;
		const footer=[
			<Button key="submit" type="primary" onClick={this.saveDialog1.bind(this)}>
				{getLabel(86, "保 存")}
			</Button>]
		const footer1=[
			<Button key="submit" type="primary" onClick={this.saveDialog2.bind(this)}>
				{getLabel(86, "保 存")}
			</Button>]
		return (
			<div>

				{
					!hasRight && <WeaAlertPage >
						<div>
							{getLabel(2012, '对不起，您暂时没有权限！')}
						</div>
					</WeaAlertPage>
				}{
				hasRight &&
				<WeaRightMenu datas={this.getRightMenu()}>
					<WeaTop
						title={getLabel(503627, "派工规则")}
						loading={loading}
						icon={<i className='icon-coms-workflow'/>}
						iconBgcolor={"#0079DE"}
						buttons={this.getButtons()}
						buttonSpace={10}
						showDropIcon={true}
						dropMenuDatas={this.getRightMenu()}
					>
						<WeaTab
							buttonsAd={this.getTabButtonsAd()}
							searchType={['base','advanced']}
							searchsBaseValue={form.getFormParams()[this.quickSearchPara] || ''}
							searchsAd={this.getSearchs()}
							showSearchAd={showSearchAd}
							setShowSearchAd={() => {setShowSearchAd(!showSearchAd);}}
							hideSearchAd={()=>DispatchSetStore.setShowSearchAd(false)}
							onSearch={v=>DispatchSetStore.doSearch({...form.getFormParams()})}
							onSearchChange={value => {
								form.updateFields({ [this.quickSearchPara]: { value } })
								setQuickSearchValue(value);
							}}
						/>
						<WeaTable
							loading={loading}
							sessionkey={sessionkey}
							comsWeaTableStore={tableStore}
							hasOrder={true}
							needScroll={true}
							onOperatesClick={this.getOperatesClick1.bind(this)}
						/>
					</WeaTop>

					<WeaDialog
						title={dialogtitle}
						visible={visible}
						buttons={footer}
						scalable = {true}
						moreBtn={{datas:this.getRightMenu1(),collectParams:{favname:dialogtitle, favouritetype:'2' ,importantlevel:'1'}}}
						hasScroll={true}
						icon="icon-coms-workflow"
						iconBgcolor="#0079DE"
						onCancel={this.closeDialog1.bind(this)}
						zIndex={995}
						style={{width: 600, height: 500}}
					>
						<WeaRightMenu datas={this.getRightMenu1()}>
							{this.getItems1()}
						</WeaRightMenu>
					</WeaDialog>

					<WeaDialog
						title={dialogtitle1}
						visible={visible1}
						buttons={footer1}
						moreBtn={{datas:this.getRightMenu2(),collectParams:{favname:dialogtitle, favouritetype:'2' ,importantlevel:'1'}}}
						hasScroll={true}
						icon="icon-coms-workflow"
						iconBgcolor="#0079DE"
						onCancel={this.closeDialog2.bind(this)}
						zIndex={996}
						style={{width: 520, height: 400}}
					>
						<WeaRightMenu datas={this.getRightMenu2()}>
							{this.getItems2()}
						</WeaRightMenu>
					</WeaDialog>
				</WeaRightMenu>
			}
			</div>
		)
	}

	//页面右键
	getRightMenu() {
		const { DispatchSetStore } = this.props;
		const { rightMenu,setDialogType, setVisible,tableStore,setRuleid } = DispatchSetStore;
		const selectedRowKeys = tableStore.selectedRowKeys;
		let isDisabled = selectedRowKeys.length === 0 ;
		let btnArr = [];
		rightMenu.slice().forEach(m => {
			let onClick = () => {
			};
			if (m.menuFun.indexOf('onNewRule()') >= 0) {
				onClick = () => {
					setVisible(true);
					setRuleid("");
					setDialogType('onNewRule');
				}
			}
			if (m.menuFun.indexOf('onDelete()') >= 0) {
				onClick = () => {
					this.onBatchDelete('1');
				}
			}

			btnArr.push({
				key: m.type,
				icon: <i className={m.menuIcon}/>,
				content: m.menuName,
				disabled:m.isControl == '1' && isDisabled ,
				onClick,
			});
		});
		return btnArr;
	}

	//根据dialogtype获取弹出框右键
	getRightMenu1() {
		const { DispatchSetStore } = this.props;
		const { chooseDialogRM1} = DispatchSetStore;
		let btnArr = [];
		chooseDialogRM1.slice().forEach(m => {
			let onClick = () => {
			};
			if (m.menuFun.indexOf('saveDialog1()') >= 0) {
				onClick = () => {
					this.saveDialog1();
				}
			}
			if (m.menuFun.indexOf('closeDialog1()') >= 0) {
				onClick = () => {
					this.closeDialog1();
				}
			}

			btnArr.push({
				key: m.type,
				icon: <i className={m.menuIcon}/>,
				content: m.menuName,
				onClick,
			});
		});
		return btnArr;
	}

	//根据dialogTypeDeatil获取弹出框右键
	getRightMenu2() {
		const { DispatchSetStore } = this.props;
		const { chooseDialogRM2} = DispatchSetStore;
		let btnArr = [];
		chooseDialogRM2.slice().forEach(m => {
			let onClick = () => {
			};
			if (m.menuFun.indexOf('saveDialog2()') >= 0) {
				onClick = () => {
					this.saveDialog2();
				}
			}
			if (m.menuFun.indexOf('closeDialog2()') >= 0) {
				onClick = () => {
					this.closeDialog2();
				}
			}

			btnArr.push({
				key: m.type,
				icon: <i className={m.menuIcon}/>,
				content: m.menuName,
				onClick,
			});
		});
		return btnArr;
	}

	//获取规则设置弹出框的内容
	getItems1() {
		const { DispatchSetStore } = this.props;
		const { chooseDialogCon1,form1,chooseDialogCon2,form2,dialogType,tableStore1,sessionkey1 } = DispatchSetStore;
		let items = [];
		let group = [];
		let items1 = [];
		let cust = [];
		const selectedRowKeys = tableStore1.selectedRowKeys;
		if(dialogType=='onNewRule'||dialogType=='onEditRule'){
			const {isFormInit} = form1;
			const formParams = form1.getFormParams();
			isFormInit && chooseDialogCon1.slice().map(c =>{
				c.items.map(fields => {
					items.push({
						com:(<WeaFormItem
							label={`${fields.label}`}
							labelCol={{span: `${fields.labelcol}`}}
							wrapperCol={{span: `${fields.fieldcol}`}}>
							<WeaSwitch fieldConfig={fields} form={form1} formParams={formParams}/>
						</WeaFormItem>),
						colSpan:1
					});
				});
				group.push(<WeaSearchGroup col={1} needTigger={true} title={c.title} showGroup={true} items={items}/>)
			})
		}


		if(dialogType=='onNewRule'||dialogType=='onEditRule'){
			//增加规则明细列表
			items1.push({
				com: (
					<div>
						<WeaTable
							sessionkey={ sessionkey1 }
							comsWeaTableStore={tableStore1}
							hasOrder={ true }
							needScroll={ false }
							onOperatesClick={this.getOperatesClick2.bind(this)}
						/>
					</div>
				)
			});
			cust = 	[
				<Row style={{  display: 'inline-block' }} className="wf-pc4backstage-OperationMenuSet-button">
					<Col>
						<Button style={{display:'inline-block'}} className="minus" type="primary" title={getLabel(91, "删除")} size="small" onClick={this.delRows.bind(this)} disabled={selectedRowKeys.length === 0}>
							<span className="icon-coms-form-delete-hot" /></Button>
						<Button style={{display:'inline-block'}} className="add" type="primary" title={getLabel(611, "添加")} size="small" onClick={this.addRows.bind(this)}>
							<span className="icon-coms-Add-to-hot" /></Button>
					</Col>
				</Row>
			]
			;
			group.push(<WeaSearchGroup col={1} needTigger={true} titleSpan={3} title={getLabel(579, "规则")+getLabel(17463, "明细")} showGroup={true} items={items1} customComponent={cust}/>)
		}

		return group;
	}

	addRows() {
		const { DispatchSetStore } = this.props;
		//添加规则明细
		this.saveRuleForDetail();
	}

	delRows() {
		const { DispatchSetStore } = this.props;
		const { tableStore1 } = DispatchSetStore;
		const selectedRowKeys = tableStore1.selectedRowKeys.join();
		this.ondelete("delruledetail",selectedRowKeys);
	}

	//获取规则明细弹出框的内容
	getItems2() {
		const { DispatchSetStore } = this.props;
		const { chooseDialogCon2,form2,dialogTypeDeatil } = DispatchSetStore;
		let items = [];
		let group = [];
		let fieldname = "";
		if(dialogTypeDeatil==='addRuleDetail'||dialogTypeDeatil==='editRuleDetail'){
			const {isFormInit} = form2;
			const formParams = form2.getFormParams();
			let onChange = () => {};
			isFormInit && chooseDialogCon2.slice().map(c =>{
				c.items.map(fields => {
					fieldname = fields.domkey[0];
					if("workflowid"=== fieldname){
						onChange = (ids) => {
							if(ids.workflowid){
								let workflowid = ids.workflowid.value;
								let chooseDialogCon2s = toJS(chooseDialogCon2);
								//给字段浏览按钮传参
								chooseDialogCon2[0].items[1].browserConditionParam.conditionDataParams={workflowId:workflowid,type:"1",htType:"3",isBill:"1",isDetail:"0"};
								chooseDialogCon2[0].items[1].browserConditionParam.dataParams={workflowId:workflowid,type:"1",htType:"3",isBill:"1",isDetail:"0"};

								//给节点浏览按钮传参
								chooseDialogCon2[0].items[2].browserConditionParam.conditionDataParams={workflowid:workflowid};
								chooseDialogCon2[0].items[2].browserConditionParam.dataParams={workflowid:workflowid};
							}
						}
					}
					items.push({
						com:(<WeaFormItem
							label={`${fields.label}`}
							labelCol={{span: `${fields.labelcol}`}}
							wrapperCol={{span: `${fields.fieldcol}`}}>
							<WeaSwitch fieldConfig={fields} form={form2} onChange = {onChange} formParams={formParams}/>
						</WeaFormItem>),
						colSpan:1
					});
				});
			})
		}
		group.push(<WeaSearchGroup col={1} needTigger={false} showGroup={true} items={items}/>)
		return group;
	}

	//保存规则
	saveDialog1(){
		const {DispatchSetStore} = this.props;
		const {form1,dialogType,setVisible,ruleid,tableStore,setVisible1}=DispatchSetStore;
		const selectedRowKeys = tableStore.selectedRowKeys.join();
		form1.validateForm().then(f=>{
			if(f.isValid){
				if(dialogType==='onEditRule'){
					DispatchSetStore.saveDialog1({ruleid:ruleid,dialogType:dialogType,...form1.getFormParams()});
				}else{
					if(Number(ruleid)<=0){
						DispatchSetStore.saveDialog1({dialogType:dialogType,...form1.getFormParams()});
					}
				}
				DispatchSetStore.form1.reset();
				setVisible(false);
				setVisible1(false);
			}else{
				f.showErrors();
				Modal.warning({
					title: getLabel(15172, "系统提示"),
					content: getLabel(383975, "必要信息不完整，红色标记为必填项！")
				});
			}
		})
	}

	//保存规则明细
	saveDialog2(){
		const {DispatchSetStore} = this.props;
		const {dialogTypeDeatil,ruleid,ruledetailid,tableStore1,setVisible1,form2}=DispatchSetStore;
		const selectedRowKeys = tableStore1.selectedRowKeys.join();
		form2.validateForm().then(f=>{
			if(f.isValid){
				if(dialogTypeDeatil==='editRuleDetail'){
					DispatchSetStore.saveDialog2({ruleid:ruleid,ruledetailid:ruledetailid,dialogType:dialogTypeDeatil,...form2.getFormParams()});
				}else{
					DispatchSetStore.saveDialog2({ruleid:ruleid,dialogType:dialogTypeDeatil,...form2.getFormParams()});
				}
				DispatchSetStore.form2.reset();
				setVisible1(false);
			}else{
				f.showErrors();
				Modal.warning({
					title: getLabel(15172, "系统提示"),
					content: getLabel(383975, "必要信息不完整，红色标记为必填项！")
				});
			}
		})
	}

	//新建规则明细时保存规则信息
	saveRuleForDetail(){
		const {DispatchSetStore} = this.props;
		const {form1,dialogType,setVisible1,setDialogTypeDetail,ruleid}=DispatchSetStore;
		form1.validateForm().then(f=>{
			if(f.isValid){
				DispatchSetStore.saveDialog1({ruleid:ruleid,dialogType: dialogType, ...form1.getFormParams()});
				setVisible1(true);
				setDialogTypeDetail('addRuleDetail');
			}else{
				f.showErrors();
				Modal.warning({
					title: getLabel(15172, "系统提示"),
					content: getLabel(383975, "必要信息不完整，红色标记为必填项！")
				});
			}
		})
	}

	//关闭规则设置弹出框
	closeDialog1(){
		const {DispatchSetStore} = this.props;
		const {form1,form2,setVisible,setVisible1,setRuleid}=DispatchSetStore;
		setVisible(false);
		setRuleid("");
		form1.reset();
		form2.reset();
	}

	//关闭规则明细设置弹出框
	closeDialog2(){
		const {DispatchSetStore} = this.props;
		const {dialogTypeDeatil,form2,setVisible1,setRuledetailid}=DispatchSetStore;
		setVisible1(false);
		setRuledetailid("");
		form2.reset();
	}

	//高级搜索查询项
	getSearchs(){
		const { DispatchSetStore } = this.props;
		const { conditioninfo,form } = DispatchSetStore;
		const {isFormInit} = form;
		let group = [];
		const formParams = form.getFormParams();
		isFormInit && toJS(conditioninfo).map(c =>{
			let items = [];
			c.items.map(fields => {
				if (fields.isQuickSearch) {
					this.quickSearchPara = fields.domkey[0];
				}
				items.push({
					com:(<WeaFormItem
						label={`${fields.label}`}
						labelCol={{span: `${fields.labelcol}`}}
						wrapperCol={{span: `${fields.fieldcol}`}}>
						<WeaSwitch fieldConfig={fields} form={form} formParams={formParams}/>
					</WeaFormItem>),
					colSpan:1
				})
			});
			group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
		});
		return group;

	}

	//高级搜索底部按钮
	getTabButtonsAd(){
		const { DispatchSetStore } = this.props;
		const { form, doSearch, setShowSearchAd } = DispatchSetStore;
		return [
			(<Button type="primary" onClick={()=>{
				DispatchSetStore.doSearch({...form.getFormParams()});
				setShowSearchAd(false);
			}}>{getLabel(197, "搜索")}</Button>),
			(<Button type="ghost" onClick={() => form.reset()}>{getLabel(2022, "重置")}</Button>),
			(<Button type="ghost" onClick={() => {
				setShowSearchAd(false);
			}}>{getLabel(201, "取消")}</Button>)
		]
	}

	//顶部右侧菜单
	getButtons() {
		const { DispatchSetStore} = this.props;
		const { rightMenu, setDialogType,setVisible, tableStore} = DispatchSetStore;
		const selectedRowKeys = tableStore.selectedRowKeys;
		let isDisabled = selectedRowKeys.length === 0 ;
		let btnArr = [];
		rightMenu.slice().forEach(m => {
			let onClick = () => {
			};
			let content = m.menuName;
			if (m.menuFun.indexOf('onNewRule()') >= 0) {
				onClick = () => {
					setVisible(true);
					setDialogType('onNewRule');
				}
			}
			if (m.menuFun.indexOf('onDelete()') >= 0) {
				onClick = () => {
					this.onBatchDelete('1');
				}
			}

			btnArr.push(<Button type="primary"
								disabled={(m.isControl == '1' && isDisabled )}
								onClick={onClick}>
				{content}
			</Button>);
		});
		return btnArr;
	}

	//批量删除规则或者规则明细
	onBatchDelete(type){
		const {DispatchSetStore} = this.props;
		const {tableStore,tableStore1} = DispatchSetStore;
		if("1"==type){
			//删除规则
			const selectedRowKeys = tableStore.selectedRowKeys.join();
			this.ondelete("delrule",selectedRowKeys);
		}else{
			//删除规则明细
			const selectedRowKeys1 = tableStore1.selectedRowKeys.join();
			this.ondelete("delruledetail",selectedRowKeys1);
		}
	}

	ondelete(type,ids){
		const {DispatchSetStore} = this.props;
		confirm({
			title : getLabel(131329, "信息确认"),
			content : getLabel(385625, "确定要删除选择的记录吗？"),
			onOk(){
				if("delrule"==type){
					DispatchSetStore.deleteRule({type:type,tempids : ids});
				}else if("delruledetail"==type){
					DispatchSetStore.deleteRuleDetail({type:type,tempids : ids});
				}

			},
			onCancel() {}
		})
	}

	//分页组件操作菜单
	getOperatesClick1(record,index,operate,flag){
		const {DispatchSetStore} = this.props;
		const {setVisible,setRuleid,setDialogType} = DispatchSetStore;
		const funName = operate.href.replace(/(javascript\:)|(\(\))/g, () => '');
		if(funName.indexOf('onEdit') >= 0) {
			setVisible(true);
			setRuleid(record.id);
			setDialogType('onEditRule');
		}  else if(funName.indexOf('onDelete')>= 0 ) {
			this.ondelete("delrule",record.id);
		}
	}

	//分页组件操作菜单
	getOperatesClick2(record,index,operate,flag){
		const {DispatchSetStore} = this.props;
		const {setVisible1,setRuledetailid,setDialogTypeDetail} = DispatchSetStore;
		const funName = operate.href.replace(/(javascript\:)|(\(\))/g, () => '');
		if(funName.indexOf('onEdit') >= 0) {
			setVisible1(true);
			setRuledetailid(record.id);
			setDialogTypeDetail('editRuleDetail');
		}  else if(funName.indexOf('onDelete')>= 0 ) {
			this.ondelete("delruledetail",record.id);
		}
	}

}

//组件检错机制
class MyErrorHandler extends React.Component {
	render() {
		const hasErrorMsg = this.props.error && this.props.error !== "";
		return(
			<WeaErrorPage msg={ hasErrorMsg ? this.props.error : getLabel(384697, "对不起，该页面异常，请联系管理员！") } />
		);
	}
}



DispatchSet = WeaTools.tryCatch( React, MyErrorHandler, { error: "" })(DispatchSet);


export default DispatchSet